package com.superme.filemanager.controller.test;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

@RestController
public class ThumbnailGenerator {

    @PostMapping("thumbnail")
    public  void main(MultipartFile imgFile) throws MalformedURLException {
        String thumbnailPath = "C:\\Users\\43128\\Desktop\\file\\thumbnail.jpg";
        int maxDimension = 200; // 缩略图的最大尺寸

        URL url = new URL("https://files.codelife.cc/wallpaper/wallspic/20240821ga3efa.jpeg?x-oss-process=image/resize,limit_0,m_fill,w_2560,h_1440/quality,Q_92/format,webp");
        try {
            BufferedImage originalImage = ImageIO.read(imgFile.getInputStream());
            int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
            BufferedImage resizedImage = resizeImage(originalImage, maxDimension);

            File thumbnailFile = new File(thumbnailPath);
            ImageIO.write(resizedImage, "jpg", thumbnailFile);
            System.out.println("Thumbnail created successfully.");
        } catch (IOException e) {
            System.err.println("Error reading or writing files: " + e.getMessage());
        }
    }

    private static BufferedImage resizeImage(BufferedImage originalImage, int maxDimension) {
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        double ratio = (double) width / height;

        if (width > height) {
            if (width > maxDimension) {
                width = maxDimension;
                height = (int) (width / ratio);
            }
        } else {
            if (height > maxDimension) {
                height = maxDimension;
                width = (int) (height * ratio);
            }
        }

        Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = resizedImage.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();

        return resizedImage;
    }
}